package com.maomao.book.aop;

import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author mao.kaiyin
 */
@Aspect
@Component
@Slf4j
public class RestApiLog {


    @Pointcut("execution(public * com.maomao.book.controller.*.*(..))")
    public void log() {
    }

    /**
     * before invoke the method of controller
     *
     * @param jp Join Point
     * @throws Throwable
     */
    @Before("log()")
    public void deBefore(JoinPoint jp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("URL : {}", request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("CLASS_METHOD : " + jp);
        log.info("ARGS : " + Arrays.toString(jp.getArgs()));

    }

    /**
     * do while after controller method
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "log()")
    public void doAfterReturning(Object ret) throws Throwable {
        JsonMapper jsonMapper = new JsonMapper();
        log.info("The rest API response data: " + jsonMapper.writeValueAsString(ret));
    }

    /**
     * exception notice
     *
     * @param jp join point
     * @param ex exception throw
     */
    @AfterThrowing(throwing = "ex", pointcut = "log()")
    public void afterThrowing(JoinPoint jp, Exception ex) {
        log.error("The rest API throws exception");
    }

}
